package info.nixbear.tgcms.domain;

import info.nixbear.tgcms.services.dao.PMF;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Version;
import javax.jdo.annotations.VersionStrategy;

import com.google.appengine.api.datastore.Text;

/**
 * Key value pair
 */
@PersistenceCapable(identityType=IdentityType.APPLICATION, detachable="true")
@Version( 
		strategy=VersionStrategy.VERSION_NUMBER, 
		column = "version", 
		extensions={@Extension(vendorName="datanucleus", key="field-name", 
				value="version")}
)
public class StringTextKvp {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
    private String encodedKey;
    
	private Long version;

	@Persistent private String key;
	
	@Persistent private Text value;
	
	@NotPersistent static final Logger logger = Logger.getLogger(StringTextKvp.class.getName());
	

	public StringTextKvp() {
		
	}
	
	public StringTextKvp(String key, Text value) {
		this.key = key;
		this.value = value;
	}
	
	
	public static StringTextKvp findStringTextKvp(String id) {
		if (id == null) {
			return null;
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StringTextKvp kvp = pm.getObjectById(StringTextKvp.class, id);

			return pm.detachCopy(kvp);
		} catch(JDOObjectNotFoundException e) {
			logger.log(Level.INFO, "not found", e);
		} finally {
			pm.close();
		}
		return null;
	}
	
	
	
	
	

	public String getId() {
		return encodedKey;
	}

	public Long getVersion() {
		return version;
	}

	public void setVersion(Long version) {
		this.version = version;
	}
	
	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public Text getValue() {
		return value;
	}

	public void setValue(Text value) {
		this.value = value;
	}
	
	
	public String getValueAsString() {
		return (this.getValue()==null)?null:this.getValue().getValue();
	}

	public void setValueAsString(String value) {
		this.setValue(new Text(value));
	}


}
